import './styles.css'
import * as THREE from 'three'
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

//定义渲染器尺寸
const size = {
  width: window.innerWidth,
  height: window.innerHeight,
}

//初始化渲染器 canvas
const canvas = document.querySelector('canvas.webgl')
const renderer = new THREE.WebGLRenderer({ canvas })
renderer.setSize(size.width, size.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

//初始化场景
const scene = new THREE.Scene()

//初始化相机 透视相机 
const camera = new THREE.PerspectiveCamera(45, size.width/size.height)
camera.position.set(3, 3, 3)
camera.lookAt(0, 0, 0)
scene.add(camera) //场景添加相机

//创建mesh模型(由几何体+材质)  正方体
const geometry = new THREE.BoxGeometry(1, 1, 1, 5, 5, 5)  //长宽高为1的立方体
const material = new THREE.MeshBasicMaterial({
  color: 0x03c03c, // 材质的颜色
  transparent:true,// 开启透明
  opacity:0.5,// 设置透明度
  wireframe: true, //显示网格虚线
})
const mesh = new THREE.Mesh(geometry, material)
mesh.position.set(0,0,0)
scene.add(mesh)

// //添加坐标轴 辅助查看
const axesHelper = new THREE.AxesHelper(150)
scene.add(axesHelper)

// renderer.render(scene, camera)

//添加轨道 用来用鼠标控制相机
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true



// 动态渲染
const tick = () => {
  renderer.render(scene, camera)
  mesh && (mesh.rotation.x += 0.02)     //以x轴旋转
  // mesh && (mesh.rotation.y += 0.02)     //以y轴旋转
  // mesh && (mesh.rotation.z += 0.02)     //以z轴旋转
  // controls.update()
  window.requestAnimationFrame(tick)
}
tick()



//页面缩放事件监听  更新渲染器和相机
window.addEventListener('resize', () => {
  size.width = window.innerWidth
  size.height = window.innerHeight
  //渲染器尺寸和像素比更新
  renderer.setSize(size.width, size.height)
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
  camera.aspect = size.width/size.height
  camera.updateProjectionMatrix() // 手动更新相机对象的投影矩阵属性
})